#爬取京东购物车信息
import requests
from pyquery import PyQuery
from requests.exceptions import RequestException 

def getPage():
	user_agents = [
	    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
	    'Opera/9.25 (Windows NT 5.1; U; en)',
	    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
	    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
	    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
	    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
	    'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7',
	    'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0',
	]
	import random
	agent = random.choice(user_agents) # 随机获取一个浏览器用户信息

	url = "https://cart.jd.com/cart.action"
	headers ={
		'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
		'accept-encoding': 'deflate, br',
		'accept-language': 'zh-CN,zh;q=0.9',
		'cache-control': 'max-age=0',
		'referer': 'https://cart.jd.com/addToCart.html?rcd=1&pid=7441493&pc=1&eb=1&rid=1546178500148&em=',
		'upgrade-insecure-requests': '1',
		'user-agent': agent,
		'cookie':'__jda=122270672.15461815205802142650488.1546181521.1546181521.1546181521.1; __jdc=122270672; __jdv=122270672|baidu|-|organic|not set|1546181520582; __jdu=15461815205802142650488; PCSYCityID=1607; shshshfpa=a25af73c-0a83-5749-37a6-bf342ab9a8f3-1546181523; user-key=0bdd57da-3e62-4676-9e10-47fafe0d2312; ipLoc-djd=1-72-4137-0; areaId=1; _gcl_au=1.1.1214331421.1546182071; shshshfpb=sf3TS%2B5zVg8Z1J0wN7fp9og%3D%3D; ipLocation=%u5317%u4EAC; 3AB9D23F7A4B3C9B=GKZCIWXQXG7W2CSEJ2KI55UVV34KWTNVWZWOGOHZ2NJRGRCE367T3UM3VXXPHFODY4AHF6FPN4Q4NUSNVCXIRHC7EU; cart-main=xx; cd=0; shshshfp=ebe2577628c0da7a9f651974526a9206; shshshsID=827c1bcfa94cc8fa28f0d53db3aff277_7_1546182138327; __jdb=122270672.9.15461815205802142650488|1.1546181521; cn=12',
	}
	try:
		res = requests.get(url,headers=headers)
		if res.status_code == 200:
			return res.text
		else:
			return None
	except RequestException:
		return None
	

def parsePage(content):
	doc = PyQuery(content)
	items = doc("div.item-form")
	for item in items.items():
		yield{
			'商品':item("div.p-name").text(),
			'价格':item("p.plus-switch").text(),
			'数量':item("span.weight").attr('num'),
			'图片':item("img").attr('src'),
		}

def main():
	content = getPage()
	items = parsePage(content)
	if items:
		for item in items:
			print(item)
	

if __name__=="__main__":
	main()





















